package com.server.Netty;

import com.server.config.NettyAndWebSocketConfig;
import com.server.config.WebSocketStartConfig;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import jakarta.annotation.PreDestroy;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;

import java.io.IOException;

@Component
public class NettyServerStart implements Runnable {
    @Autowired
    NettyAndWebSocketConfig nWConfig;
    @Autowired
    WebSocketStartConfig webSocketStartConfig;

    private  EventLoopGroup boosGroup;
    private  EventLoopGroup workGroup;

    @PreDestroy
    public void close(){
        boosGroup.shutdownGracefully();
        workGroup.shutdownGracefully();
    }

    @Override
    public void run() {

        boosGroup= new NioEventLoopGroup(nWConfig.getNettyBoosGroup());
        workGroup= new NioEventLoopGroup(nWConfig.getNettyWorkGroup());
        try {
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            serverBootstrap.group(boosGroup,workGroup)
                    .channel(NioServerSocketChannel.class)
                    .option(ChannelOption.SO_BACKLOG,nWConfig.getChannelOptionBacklog())
                    .childHandler(webSocketStartConfig);
            ChannelFuture channelFuture = serverBootstrap.bind(nWConfig.getPort()).sync();
            channelFuture.channel().closeFuture().sync();
        }catch ( InterruptedException e){
            throw new RuntimeException(e);
        } finally {
            boosGroup.shutdownGracefully();
            workGroup.shutdownGracefully();
        }



    }
}
